package apis

import (
	"gitee.com/sansaniot/ssiot-core/sdk/api"
	"gitee.com/sansaniot/ssiot-core/sdk/pkg/jwtauth/user"
	_ "gitee.com/sansaniot/ssiot-core/sdk/pkg/response"
	"gitee.com/sansaniot/ssiot-core/serrors"
	"github.com/gin-gonic/gin"
	"ssadmin/common/constant"
	"ssadmin/internal/admin/models"
	"ssadmin/internal/admin/models/command"
	"ssadmin/internal/admin/service"
)

type SysLogo struct {
	api.Api
}

// Get 获取logo
func (e SysLogo) Get(c *gin.Context) {
	req := command.SysLogoReq{}
	s := service.SysLogo{}

	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors

	if err != nil {
		e.Logger.Error(err)
		e.Fail(serrors.Fail)
		return
	}

	userId := user.Get(c, constant.CacheKeyUserId).(string)
	creatorId := user.Get(c, constant.CacheKeyCreatorId).(string)
	agencyId := user.Get(c, constant.CacheKeyAgencyId).(string)

	// 非租户，非admin，查询租户的logo
	if creatorId != "1" {
		req.UserId = agencyId
	} else {
		req.UserId = userId
	}

	req.Systemid = c.GetHeader(constant.CacheKeySystemId)

	var object models.SysLogo
	err = s.Get(&req, &object)
	if err != nil {
		e.Fail(serrors.Fail)
		return
	}
	e.Data(object)
}

// Save 保存
func (e SysLogo) Save(c *gin.Context) {
	req := command.SysLogoReq{}
	s := service.SysLogo{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Fail(serrors.Fail)
		return
	}

	//请求扩展查询参数
	e.setSystemParam(c, &req)
	if req.Creator != "admin" {
		e.Fail(0, "只有租户可以修改系统信息")
		return
	}

	err = s.Save(&req)
	if err != nil {
		e.Fail(serrors.Fail)
		return
	}

	e.Data(req.Id)
}

func (e *SysLogo) setSystemParam(c *gin.Context, req *command.SysLogoReq) {
	req.UserId = user.Get(c, constant.CacheKeyUserId).(string)
	req.UserName = user.Get(c, constant.CacheKeyUserName).(string)
	req.Creator = user.Get(c, constant.CacheKeyCreator).(string)
	req.Systemid = c.GetHeader(constant.CacheKeySystemId)
}
